/*
 * Copyright (c) 2013   Tobias Welther
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package de.tudarmstadt.kom.androidsensorapi.sensor.listener.orientation;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import java.util.Date;

import de.tudarmstadt.kom.androidsensorapi.sensor.data.concrete.OrientationSensorData;
import de.tudarmstadt.kom.androidsensorapi.sensor.listener.AbstractSensor;
import de.tudarmstadt.kom.androidsensorapi.sensormanagement.SensorTypeToData;

/**
 * Created by Tobias Welther
 */
public class OrientationSensor extends AbstractSensor<OrientationSensorData>
        implements SensorEventListener{

    /**
     * The cached value of the Accelerometer to recalculate the value for the orientation.
     * The initial value is set to be sure to avoid NullPointer exceptions.
     */
    private float[] lastAccelerometerData = new float[3];
    private boolean accelerometerDataPresent = false;


    /**
     * The cached value of the Magnet Field SensorInterface to recalculate the value for the orientation.
     * The initial value is set to be sure to avoid NullPointer exceptions.
     */
    private float[] lastMagnetometerData = new float[3];
    private boolean magnetometerDataPresent = false;

    /**
     * The cached Rotation matrix
     */
    private float[] rotationMatrix = new float[9];


    public OrientationSensor() {
        super(SensorTypeToData.Orientation);
    }


    @Override
    public void onSensorChanged(SensorEvent event) {
        //there is no direct Orientation SensorInterface any more.
        //We need to listen to accelerometer + magnet field changes and recalculate afterwards.

        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            System.arraycopy(event.values, 0, lastAccelerometerData, 0, event.values.length);
            accelerometerDataPresent = true;
        } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            System.arraycopy(event.values, 0, lastMagnetometerData, 0, event.values.length);
            magnetometerDataPresent = true;
        }

        boolean recalculationDataPresent = accelerometerDataPresent && magnetometerDataPresent;
        if (recalculationDataPresent) {
            //We have a valid accelerometer + magnetometer data. Let's calculate the Orientation.
            float[] resultingOrientation = new float[3];

            //The Orientation is calculated by the rotation Matrix
            SensorManager.getRotationMatrix(rotationMatrix, null, lastAccelerometerData, lastMagnetometerData);
            SensorManager.getOrientation(rotationMatrix, resultingOrientation);

            this.lastData = new OrientationSensorData(new Date(event.timestamp), resultingOrientation[0],
                    resultingOrientation[1], resultingOrientation[2]);
        }
    }


    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //not needed here.
    }
}
